package me.zhengjie.modules.xiao.rest;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.UserQueryCriteria;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.xiao.domain.CgFollowupform;
import me.zhengjie.modules.xiao.domain.vo.CgFollowupformQueryCriteria;
import me.zhengjie.modules.xiao.service.CgFollowupformService;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.VxMsg;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DatePattern.NORM_DATE_PATTERN;

/**
* @author cg
* @date 2024-06-19
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "跟进管理")
@RequestMapping("/api/cgFollowupform")
public class CgFollowupformController {

    private final CgFollowupformService cgFollowupformService;
    private final UserService userService;
    private final DeptService deptService;
    private final VxMsg vxMsg;
    private final DictDetailService dictDetailService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('cgFollowupform:list')")
    public void exportCgFollowupform(HttpServletResponse response, CgFollowupformQueryCriteria criteria) throws IOException {
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        List<Long> jobs = userDetails.getUser().getJobs().stream().map(Job::getId).collect(Collectors.toList());
        Long deptId = userDetails.getUser().getDept().getId();
        Integer level = userDetails.getLevel();
        if(jobs.contains(8L)){
            if (level == 3||level == 4) {
                UserQueryCriteria userCriteria = new UserQueryCriteria();
                List<Dept> data = deptService.findByPid(deptId);
                // 然后把子节点的ID都加入到集合中
                userDetails.getDataScopes().get(0);
                List<Long> deptIds = deptService.getDeptChildren(data);
                deptIds.add(deptId);
                deptIds.retainAll(userDetails.getDataScopes());
                userCriteria.getDeptIds().addAll(deptIds);
                if(level == 3){
                   deptIds.add(0L);
                }
                criteria.getDeptIds().addAll(deptIds);
                criteria.getCreateBys().add(userDetails.getUser().getUsername());
            }
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }
        if(StringUtils.isNotBlank(criteria.getTime())){
            List<Date> createTimeList = new ArrayList<>();
            Date date = DateUtil.parse(criteria.getTime(),NORM_DATE_PATTERN);
            createTimeList.add( DateUtil.beginOfDay(date));
            createTimeList.add( DateUtil.endOfDay(date));
            criteria.setCreateTimeList(createTimeList);
        }
        cgFollowupformService.download(cgFollowupformService.queryAll(criteria), response);
    }

    @GetMapping(value = "/page")
    @Log("查询跟进")
    @ApiOperation("查询跟进")
    @PreAuthorize("@el.check('cgFollowupform:list')")
    public ResponseEntity<PageResult<CgFollowupform>> queryCgFollowupform(CgFollowupformQueryCriteria criteria, Page<Object> page){
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        List<Long> jobs = userDetails.getUser().getJobs().stream().map(Job::getId).collect(Collectors.toList());
        Long deptId = userDetails.getUser().getDept().getId();
        Integer level = userDetails.getLevel();
        if(jobs.contains(8L)){
            if (level == 3||level == 4) {
                UserQueryCriteria userCriteria = new UserQueryCriteria();
                List<Dept> data = deptService.findByPid(deptId);
                // 然后把子节点的ID都加入到集合中
                userDetails.getDataScopes().get(0);
                List<Long> deptIds = deptService.getDeptChildren(data);
                deptIds.add(deptId);
                deptIds.retainAll(userDetails.getDataScopes());
                userCriteria.getDeptIds().addAll(deptIds);
                if(level == 3){
                   deptIds.add(0L);
                }
                criteria.getDeptIds().addAll(deptIds);
                criteria.getCreateBys().add(userDetails.getUser().getUsername());
            }
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }
        if(StringUtils.isNotBlank(criteria.getTime())){
            List<Date> createTimeList = new ArrayList<>();
            Date date = DateUtil.parse(criteria.getTime(),NORM_DATE_PATTERN);
            createTimeList.add( DateUtil.beginOfDay(date));
            createTimeList.add( DateUtil.endOfDay(date));
            criteria.setCreateTimeList(createTimeList);
        }
        PageResult<CgFollowupform> pageResult = cgFollowupformService.queryAll(criteria,page);
        for(CgFollowupform followupform:pageResult.getContent()){
            User user = userService.findByName(followupform.getCreateBy());
            if (user !=null){
                followupform.setCreateUserName(user.getNickName());
            }

        }
        return new ResponseEntity<>(pageResult,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增跟进")
    @ApiOperation("新增跟进")
    @PreAuthorize("@el.check('cgFollowupform:add')")
    public ResponseEntity<Object> createCgFollowupform(@Validated @RequestBody CgFollowupform resources){
        String userName = SecurityUtils.getCurrentUsername();
        Long createdeptId = SecurityUtils.getCurrentDeptId();
        String createdeptName = SecurityUtils.getCurrentDeptName();
        String latestFollowPerson = userService.findByName(userName).getNickName();
        resources.setLatestFollowPerson(latestFollowPerson);
        resources.setCreateBy(userName);
        resources.setCreateTime(DateUtil.date().toTimestamp());
        resources.setCreateDeptId(createdeptId);
        resources.setCreateDeptName(createdeptName);
        cgFollowupformService.create(resources);
        DictDetail dictDetail = dictDetailService.getById(22);
        if("1".equals(dictDetail.getValue())){
            List<String> usernames = userService.getUserNameByDeptId(resources.getDeptId());
            for(String sendUserName:usernames){
                vxMsg.sendFollowMsg(sendUserName,resources.getId(),resources.getCustomerName(),latestFollowPerson,"cc",DateUtil.formatDate(new Date()),createdeptName);
            }
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping
    @Log("修改跟进")
    @ApiOperation("修改跟进")
    @PreAuthorize("@el.check('cgFollowupform:edit')")
    public ResponseEntity<Object> updateCgFollowupform(@Validated @RequestBody CgFollowupform resources){
        String userName = SecurityUtils.getCurrentUsername();
        resources.setUpdateBy(userName);
        resources.setUpdateTime(DateUtil.date().toTimestamp());
        cgFollowupformService.update(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping
    @Log("删除跟进")
    @ApiOperation("删除跟进")
    @PreAuthorize("@el.check('cgFollowupform:del')")
    public ResponseEntity<Object> deleteCgFollowupform(@RequestBody List<Integer> ids) {
        cgFollowupformService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @GetMapping(value = "/findByid")
    @Log("跟进详情")
    @ApiOperation("跟进详情")
    public ResponseEntity<CgFollowupform> findCgCluetable(@RequestParam("id") Integer id){
        CgFollowupform entity= cgFollowupformService.getById(id);
        return new ResponseEntity<>(entity,HttpStatus.OK);
    }
}